<!-- src/components/AsyncImage.vue -->
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { fileApi } from '@/api/file-api'
import { ElImage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'

interface Props {
  imageKey?: string
}

const props = defineProps<Props>()

const imageUrl = ref('')
const loading = ref(true)
const error = ref(false)

const fetchImageUrl = async () => {
  if (!props.imageKey) {
    loading.value = false
    return
  }

  try {
    loading.value = true
    error.value = false
    const strings = props.imageKey.split(':')
    imageUrl.value = await fileApi.downloadUrl(strings[0], strings[1])
  } catch (err) {
    console.error('获取图片URL失败:', err)
    error.value = true
    imageUrl.value = ''
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchImageUrl()
})

watch(
  () => props.imageKey,
  () => {
    fetchImageUrl()
  },
)
</script>

<template>
  <div class="async-image-container">
    <el-image
      v-if="!loading && !error && imageUrl"
      :src="imageUrl"
      style="width: 80px; height: 80px"
      fit="cover"
      :preview-src-list="[imageUrl]"
    />
    <div v-else-if="loading" class="image-placeholder">
      <el-skeleton style="width: 80px; height: 80px" animated>
        <template #template>
          <el-skeleton-item variant="image" style="width: 80px; height: 80px" />
        </template>
      </el-skeleton>
    </div>
    <div v-else class="image-placeholder">
      <el-icon style="font-size: 24px; color: #c0c4cc">
        <Picture />
      </el-icon>
    </div>
  </div>
</template>

<style scoped>
.async-image-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}
</style>
